<template>
  <div class="bottom-bar">
    <div class="check-content">
      <check-button :is-checked="isSelectAll" class="check-botton" @click.native="checkClick "></check-button>
      <span>全选</span>
    </div>

    <div class="price">
      合计:{{totalPrice}}
    </div>

    <div class="calculate" @click="calcClick">
      去计算({{checkLength}})
    </div>
  </div>
</template>

<script>
  import CheckButton from 'components/content/checkButton/CheckButton'
  
  import { mapGetters } from 'vuex'
  export default{
    name: 'CartButtomBar',
    components: {
      CheckButton
    },
    computed: {
      ...mapGetters(['cartList']),
      totalPrice() {
        return '￥' + this.cartList.filter(item => {
          return item.checked
        }).reduce((preValue, item) => {
          return preValue + item.price * item.count
        }, 0).toFixed(2)
      },
      checkLength() {
        return this.cartList.filter(item => item.checked).length
      },
      isSelectAll() {
        // 全选方案一: 使用高阶函数filter 效率较低,因为要全部遍历 
        // if (this.cartList.length === 0) return false;
        // return !(this.cartList.filter(item => !item.checked).length)

        // 全选方案二: 使用高阶函数find 效率高,找到一个未选中便取消全选
        // if (this.cartList.length === 0) return false;
        // return !this.cartList.find(item => !item.checked)

        // 普通遍历方式
        if (this.cartList.length === 0) return false;
        for(let item of this.cartList) {
          if(!item.checked) {
            return false
          }
        }
        return true
      }
    },
    methods: {
      checkClick() {
        if (this.isSelectAll) { // 全部选中
          this.cartList.forEach(item => item.checked = false)
        } else { // 部分或者全部不选中 
          this.cartList.forEach(item => item.checked = true)
        }

        // 不能用以下代码简化
        // this.cartList.forEach(item => item.checked = !this.isSelectAll)
      },
      calcClick() {
        if (!this.cartList.find(item => item.checked)) {
          this.$toast.show('请选择购买的商品', 2000)
        }
      }
    }
  }
</script>

<style scoped>
  .bottom-bar {
    position:absolute;
    left: 0;
    right: 0;
    bottom: 49px;
    height: 40px;
    line-height: 40px;
    display: flex;
    background-color: #eee;
    font-size: 15px;
  }

  .check-content {
    display: flex;
    width: 60px;
    align-items: center;
    margin-left: 10px;
  }

  .check-botton {
    width: 20px;
    height: 20px;
    line-height: 20px;
    margin-right: 5px; 
  }

  .price {
    margin-left: 20px;
    flex: 1;
  }

  .calculate {
    width: 90px;
    background-color: red;
    color: #fff;
    text-align: center;
  }
</style>
